package com.itcast.myrpc.client;

import com.itcast.myrpc.encoder.IntegerToByteBufEncoder;
import com.itcast.myrpc.handler.ClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @program: bio_tcp
 * @description:
 * @author: zhanghz001
 * @create: 2021-02-22 09:04
 **/
public class MyRpcClient {
    public void start(String host, int port) throws Exception {
        //定义工作线程组
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        
        try {
            //获取启动类,client 启动类是Bootstrap
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(workerGroup)//绑定工作线程组
                    .channel(NioSocketChannel.class)//客户端连接通道,服务器的不一样
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline()
                                    .addLast(new IntegerToByteBufEncoder())
                                    .addLast(new ClientHandler());
                            
                        }
                    });//这个是通道的handler
            ;
            //开启
            ChannelFuture future = bootstrap.connect(host, port).sync();
            System.out.println("客户端连接服务器成功");
            
            //监控关闭
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //优雅关闭
            workerGroup.shutdownGracefully();
        }
    }
}
